package com.lynn.salary.util;

import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Proxy;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

public class ObjectFactory {

	private static Properties beansProp = null;
	private static Map<String, Object> beans = new HashMap<String, Object>();
	private static Map<String, Object> targets = new HashMap<String, Object>();

	static {
		beansProp = new Properties();
		try {
			InputStream is = ObjectFactory.class.getResourceAsStream("/beans.properties");
			beansProp.load(is);
			is.close();
		} catch (IOException e1) {
			System.err.println("ObjectFactory::static 加载配置出错");
		}
		for (Object key : beansProp.keySet()) {
			String c = beansProp.getProperty((String) key);
			try {
				Class<?> newClass = Class.forName(c);
				Object obj = newClass.newInstance();
				MyInvocationHandler inv = new MyInvocationHandler();
				inv.setTarget(obj);
				Object proxy = Proxy.newProxyInstance(obj.getClass().getClassLoader(), obj.getClass().getInterfaces(), inv);
				targets.put((String) key, obj);
				beans.put((String) key, proxy);
				System.err.println(key + "=" + c);
			} catch (ClassNotFoundException e) {
				System.err.println("ObjectFactory::static 找不到类型" + c);
			} catch (InstantiationException e) {
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				e.printStackTrace();
			}
		}
	}

	public static Object getBean(String name) {
//		System.out.println("getBean:" + name);
//		System.out.println(">>>>>>>>"+beans.get(name));
		return 
				beans.get(name);
	}

	public static Object getTarget(String name) {
		System.out.println("getTarget:" + name);
		return targets.get(name);
	}

	public static void destory() {
		for(String key : targets.keySet()) {
			BeansInterface bi = (BeansInterface) targets.get(key);
			bi.destory();
		}
		System.out.println("\t\tdestory ObjectFactory completed ... ");
	}
}
